import 'dart:math';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:ileddemo/code/ui/base/BaseWidget.dart';
import 'package:lib_bt/listener/OnBleConnectListener.dart';
import 'package:lib_bt/listener/OnBleScanListener.dart';
import 'package:lib_bt/BleManager.dart';
import 'package:lib_util/ToastUtil.dart';
import '../../../generated/l10n.dart';
import '../../ble/protocol/AutoConnectUtil.dart';
import '../../ble/protocol/base/LedBleBeanInterface.dart';
import '../../util/PermissionUtil.dart';
import '../base/TitleBarWidget.dart';

//蓝牙列表
class ConnectBlePage extends StatefulWidget {
  const ConnectBlePage({super.key});

  @override
  State<ConnectBlePage> createState() => _ConnectBlePageState();
}

class _ConnectBlePageState extends State<ConnectBlePage>
    with TickerProviderStateMixin
    implements OnBleConnectListener, OnBleScanListener {
  late AnimationController _controller;
  late Animation<double> _animation;
  CancelFunc? connectDialog;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 500));
    _animation = Tween<double>(begin: 0.0, end: 1.0).animate(_controller)
      ..addListener(() {
        setState(() {
          // The state that has changed here is the animation variable.
        });
      });
    BleManager.instance.addConnectListener(this);
    BleManager.instance.addScanListener(this);

    Future.delayed(const Duration(seconds: 0), () {
      if (BleManager.instance.isScanning()) {
        onStartScan();
      } else {
        BleManager.instance.startScan();
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    BleManager.instance.stopScan();
    BleManager.instance.removeConnectListener(this);
    BleManager.instance.removeScanListener(this);
    super.dispose();
  }

  Future<void> scan() async {
    //开始扫描
    bool flag = await PermissionUtil.instance.checkBlePermission(context);
    if (!flag) {
      return;
    }
    BleManager.instance.startScan();
  }

  @override
  Widget build(BuildContext context) {
    return BaseWidget(
      child: Column(
        children: [
          TitleBarWidget(
            title: S.of(context).str_id_0,
            rightWidget: [
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () async {
                  //开始扫描
                  scan();
                },
                child: SizedBox(
                  height: 55,
                  width: 55,
                  child: Transform(
                    alignment: Alignment.center,
                    transform: Matrix4.rotationZ(_animation.value * 360 * (pi / 180)),
                    child: const Icon(size: 30, color: Colors.black, Icons.autorenew_outlined),
                  ),
                ),
              ),
            ],
          ),
          Expanded(
            child: ListenableBuilder(
              listenable: BleManager.instance,
              builder: (BuildContext context, Widget? child) {
                return RefreshIndicator(
                  onRefresh: () async {
                    //开始扫描
                    scan();
                  },
                  child: ListView.builder(
                    physics: const AlwaysScrollableScrollPhysics(),
                    itemCount: BleManager.instance.bleBeans.length,
                    itemBuilder: (context, index) {
                      LedBleBeanInterface bean = BleManager.instance.bleBeans[index] as LedBleBeanInterface;
                      return Row(
                        children: [
                          const SizedBox(width: 10),
                          //名称和分辨率
                          Row(
                            children: [
                              Text(bean.name, style: const TextStyle(color: Colors.black, fontSize: 14)),
                              const SizedBox(width: 15),
                              Text(
                                "${bean.height}x${bean.width}",
                                style: const TextStyle(color: Colors.black, fontSize: 10),
                              ),
                              Text("   ${bean.rssi}", style: const TextStyle(color: Colors.black, fontSize: 10)),
                            ],
                          ),
                          const Spacer(),
                          //连接按钮
                          Switch(
                            value: bean.isConnect,
                            onChanged: (bool value) {
                              if (bean.isConnect) {
                                BleManager.instance.disconnect(bean.address);
                                AutoConnectUtil.instance.saveAutoConnect("");
                              } else {
                                var bleList = BleManager.instance.getConnectBleBeans();
                                //跟已经连接的设备类型不一致的不自动连
                                if (bleList.isNotEmpty) {
                                  var lastBle = BleManager.instance.getBleBean<LedBleBeanInterface>(
                                    bleList.last.address,
                                  );
                                  if (lastBle != null) {
                                    if (lastBle.typeIsSame(bean)) {
                                      BleManager.instance.connect(bean.address);
                                    } else {
                                      // 类型不一致,不允许连接
                                      ToastUtil.showToast(S.of(context).str_common_1);
                                    }
                                  }
                                } else {
                                  BleManager.instance.connect(bean.address);
                                }
                              }
                            },
                          ),
                          const SizedBox(width: 10),
                        ],
                      );
                    },
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  @override
  void onStartConnect(String address) {
    connectDialog?.call();
    connectDialog = BotToast.showLoading();
  }

  @override
  void onConnected(String address) {
    connectDialog?.call();
  }

  @override
  void onDisconnected(String address) {
    connectDialog?.call();
  }

  @override
  void onStartScan() {
    _controller.repeat();
  }

  @override
  void onStopScan() {
    _controller.stop();
  }

  @override
  void onScanResult(result) {}

  @override
  void onMtuChanged(String address, int mtu) {}
}
